package com.voicechat.firstmet.imcontrol;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Parcel;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tencent.TIMMessage;
import com.tencent.TIMSoundElem;
import com.tencent.TIMValueCallBack;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 语音消息数据
 */
@SuppressLint("ParcelCreator")
public class VoiceMessage extends Message {

    private static final String TAG = "VoiceMessage";

    public VoiceMessage(TIMMessage message){
        this.message = message;
    }


    /**
     * 语音消息构造方法
     *
     * @param duration 时长
     * @param data 语音数据
     */
    public VoiceMessage(long duration, byte[] data){
        message = new TIMMessage();
        TIMSoundElem elem = new TIMSoundElem();
        elem.setData(data);
        elem.setDuration(duration);  //填写语音时长
        message.addElement(elem);
    }
    /**
     * 语音消息构造方法
     *
     * @param duration 时长
     * @param filePath 语音数据地址
     */
    public VoiceMessage(long duration, String filePath){
        message = new TIMMessage();
        TIMSoundElem elem = new TIMSoundElem();
        elem.setPath(filePath);
        elem.setDuration(duration);  //填写语音时长
        message.addElement(elem);
    }

    /**
     * 显示消息
     *
     * @param viewHolder 界面样式
     * @param context 显示消息的上下文
     */
    @Override
    public void showMessage(ChatAdapter.ViewHolder viewHolder, Context context) {
        viewHolder.rightAccount.setVisibility(View.GONE);
        View view = View.inflate(context,R.layout.item_voice_message,null);
        RelativeLayout relaRightVoice = view.findViewById(R.id.rela_voice_right);
        RelativeLayout relaLeftVoice = view.findViewById(R.id.rela_voice_left);
        ImageView imageRightVoice = view.findViewById(R.id.image_voice);
        ImageView imageLeftVoice = view.findViewById(R.id.image_voice_left);
        TextView tvLeftTime = view.findViewById(R.id.tv_left_time);
        TextView tvRightTime = view.findViewById(R.id.tv_right_time);
        //聊天布局背景
        LinearLayout relativeLayout1 = view.findViewById(R.id.rela_1);
        LinearLayout relativeLayout2 = view.findViewById(R.id.rela_2);
        AnimationDrawable frameAnimatio;
        //获取屏幕宽度
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        //item 设定最小最大值
        int mMaxIItemWidth = (int) (outMetrics.widthPixels * 0.5f);
        int mMinItemWidth = (int) (outMetrics.widthPixels * 0.15f);
        ViewGroup.LayoutParams layoutParams = relativeLayout1.getLayoutParams();
        ViewGroup.LayoutParams layoutParams2 = relativeLayout2.getLayoutParams();
        if (message.isSelf()){
            relaRightVoice.setVisibility(View.VISIBLE);
            relaLeftVoice.setVisibility(View.GONE);
            layoutParams.width = (int) (mMinItemWidth + (mMaxIItemWidth / 60f*((TIMSoundElem) message.getElement(0)).getDuration()));
            tvRightTime.setText(String.valueOf(((TIMSoundElem) message.getElement(0)).getDuration()) + "''");
            imageRightVoice.setBackgroundResource(R.drawable.msg_right_recording_anim);
            frameAnimatio = (AnimationDrawable) imageRightVoice.getBackground();
            frameAnimatio.selectDrawable(2);
        }else{
            relaRightVoice.setVisibility(View.GONE);
            relaLeftVoice.setVisibility(View.VISIBLE);
            layoutParams2.width = (int) (mMinItemWidth + (mMaxIItemWidth / 60f*((TIMSoundElem) message.getElement(0)).getDuration()));
            tvLeftTime.setText(String.valueOf(((TIMSoundElem) message.getElement(0)).getDuration()) + "''");
            imageLeftVoice.setBackgroundResource(R.drawable.msg_left_recording_anim);
            frameAnimatio = (AnimationDrawable) imageLeftVoice.getBackground();
            frameAnimatio.selectDrawable(2);
        }
        clearView(viewHolder);
        getBubbleView(viewHolder).addView(view);
        getBubbleView(viewHolder).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(MediaUtil.getInstance().setPlayer()){
                    MediaUtil.getInstance().stop();
                    frameAnimatio.stop();
                    frameAnimatio.selectDrawable(2);
                }else {
                    VoiceMessage.this.playAudio(frameAnimatio);
                }

            }
        });
        showStatus(viewHolder);
    }

    /**
     * 获取消息摘要
     */
    @Override
    public String getSummary() {
        return App.getInstance().getApplicationContext().getString(R.string.summary_voice);
    }
    /**
     * 保存消息或消息文件
     */
    @Override
    public void save() {

    }

    private void playAudio(AnimationDrawable frameAnimatio) {
        TIMSoundElem elem = (TIMSoundElem) message.getElement(0);
        MediaUtil.getInstance().stop();
        elem.getSound(new TIMValueCallBack<byte[]>() {
            @Override
            public void onError(int i, String s) {

            }
            @Override
            public void onSuccess(byte[] bytes) {
                try{
                    File tempAudio = FileUtils.getTempFile(FileUtils.FileType.AUDIO);
                    FileOutputStream fos = new FileOutputStream(tempAudio);
                    fos.write(bytes);
                    fos.close();
                    FileInputStream fis = new FileInputStream(tempAudio);
                    MediaUtil.getInstance().play(fis);
                     frameAnimatio.start();
                    MediaUtil.getInstance().setEventListener(new MediaUtil.EventListener() {
                        @Override
                        public void onStop() {
                            frameAnimatio.stop();
                            frameAnimatio.selectDrawable(2);
                        }
                    });
                }catch (IOException e){

                }
            }
        });
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }
}
